import { defineStore } from 'pinia'
import type { CommentData } from '../tiptap/extensions/CommentPlugin'
import api from '../api/index'
//定义数据格式
export interface MergedCommentDocument {
  noteId: string
  userId: string
  comments: CommentData[]
}
//pinia创建store
export const useCommentStore = defineStore('comment', {
  state: () => ({
    commentList: [] as CommentData[],
    noteId: '',
    userId: ''
  }),
//  persist: true, //持久化存储
  actions: {
    async load(noteId: string, userId: string) {
      this.noteId = noteId
      this.userId = userId
      console.log('Loading comments for noteId:', noteId, 'userId:', userId)
      const res= await api.commentinfo.getComments(noteId, userId)
      if (!res.data) {
        this.commentList = []
        return
      }
      this.commentList = res.data
      console.log('Loaded comments:', this.commentList)
    },
//save包含更新和新增
    async save() {
      const payload: MergedCommentDocument = {
        noteId: this.noteId,
        userId: this.userId,
        comments: this.commentList
      }
      await api.commentinfo.saveComments(payload)
    },

    addComment(comment: CommentData) {
      this.commentList.push(comment)
    },

    deleteComment(id: string) {
      this.commentList = this.commentList.filter(c => c.id !== id)
    },
    updateComment(updatedComment: CommentData) {
      const index = this.commentList.findIndex(c => c.id === updatedComment.id)
      if (index !== -1) {
        this.commentList[index] = updatedComment
      }
    },
    clearComments() {
  this.commentList = []
  localStorage.removeItem("comment")
}
  }
})
